﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_PERMISSION.Base;
using ERP_RORZE_TOOL.Tool.UserControls;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;
using BaseDAO = ERP_RORZE_TOOL.DBAccess.BaseDAO;
using Utilities = ERP_RORZE_TOOL.Common.Utilities;

namespace ERP_RORZE_TOOL.Tool.Forms
{
    public partial class frm_ImportAdd : DevExpress.XtraEditors.XtraForm
    {
        private ucImport parent;
        private DataTable dataTable;
        AutoCompleteStringCollection itemToolID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemMakerID = new AutoCompleteStringCollection();
        AutoCompleteStringCollection itemSupplierID = new AutoCompleteStringCollection();
        private bool dropDown;
        private LogUtils log;

        public frm_ImportAdd(ucImport fImport = null)
        {
            InitializeComponent();
            btTAdd.Image = ERP_RORZE_TOOL.Properties.Resources.add;
            btTCancel.Image = ERP_RORZE_TOOL.Properties.Resources.cancel;
            parent = fImport;
            //this.CancelButton = this.btTCancel;
            cmbMakerID.LostFocus += cmbMakerID_LostFocus;
            cmbToolID.LostFocus += cmbToolID_LostFocus;
            cmbTSupplierID.LostFocus += cmbTSupplierID_LostFocus;
            this.ActiveControl = cmbToolID;
            log = new LogUtils();

        }

        void cmbMakerID_LostFocus(object sender, EventArgs e)
        {
            if (cmbMakerID.Items.Count <= 0)
            {
                foreach (string s in cmbMakerID.AutoCompleteCustomSource)
                {
                    if (cmbMakerID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbMakerID.Text = s;
                        break;
                    }
                }

            }

        }

        void cmbTSupplierID_LostFocus(object sender, EventArgs e)
        {
            if (cmbTSupplierID.Items.Count <= 0)
            {
                foreach (string s in cmbTSupplierID.AutoCompleteCustomSource)
                {
                    if (cmbTSupplierID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbTSupplierID.Text = s;
                        break;
                    }
                }

            }

        }

        void cmbToolID_LostFocus(object sender, EventArgs e)
        {
            if (cmbToolID.Items.Count <= 0)
            {
                foreach (string s in cmbToolID.AutoCompleteCustomSource)
                {
                    if (cmbToolID.Text.ToUpper().Equals(s.ToUpper()))
                    {
                        cmbToolID.Text = s;
                        break;
                    }
                }

            }

            string sql = "SELECT * FROM  [333_Tool]" +
                         "WHERE [333_Tool].ToolID = N'" + cmbToolID.Text + "';";
            dataTable = BaseDAO.ExecuteQuery(sql);
            if (dataTable.Rows.Count > 0)
            {
                txtToolName.Text = dataTable.Rows[0][ToolConstants.Entities.Tool.FieldName.ToolName].ToString();
            }
            else
            {
                txtToolName.Text = string.Empty;
            }
        }

        private void XtraForm1_Load(object sender, EventArgs e)
        {
            dtpTDate.Value = DateTime.Today;
            BindDataTools();
            BindDataToMaker();
            BindDataSupplier();

        }

        private void btTAdd_Click_1(object sender, EventArgs e)
        {
            AddTool();
        }

        private void btTCancel_Click_1(object sender, EventArgs e)
        {
            this.Close();
        }

        protected override bool ProcessKeyPreview(ref Message m)
        {
            if (m.Msg == 0x0100 && (int)m.WParam == 13)
            {
                this.ProcessTabKey(true);
            }
            return base.ProcessKeyPreview(ref m);
        }

        private void frm_ImportAdd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Alt)
            {
                if (e.KeyCode == Keys.D)
                {
                    btTAdd.Focus();
                    this.btTAdd.PerformClick();
                }
            }
            else if (e.KeyCode == Keys.End)
            {
                btTAdd.Focus();
            }
            else if (e.KeyCode == Keys.Home)
            {
                dtpTDate.Focus();
            }
        }

        private void cmbToolID_DropDown(object sender, EventArgs e)
        {
            dropDown = true;

            System.Windows.Forms.ComboBox combo = sender as System.Windows.Forms.ComboBox;
            combo.AutoCompleteMode = AutoCompleteMode.None;
            if (combo.Items.Count <= 0)
            {
                Cursor.Current = Cursors.WaitCursor;
                switch (combo.Name)
                {
                    case "cmbToolID":
                        foreach (var item in itemToolID)
                        {
                            cmbToolID.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbTSupplierID":
                        foreach (var item in itemSupplierID)
                        {
                            cmbTSupplierID.Items.Add(item.ToString());

                        }
                        break;
                    case "cmbMakerID":
                        foreach (var item in itemMakerID)
                        {
                            cmbMakerID.Items.Add(item.ToString());

                        }
                        break;

                }
                Cursor.Current = Cursors.Default;


            }
        }

        #region Private methods

        private bool GetDataTool(Import o)
        {
            #region Check valid

            DataTable dtCheck;

            if (Utilities.IsNullOrEmpty(dtpTDate.Value.ToString()))
            {
                MessageBox.Show(ToolConstants.Message.Import.DateCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbToolID.Text))
            {
                MessageBox.Show(ToolConstants.Message.Import.ToolIDCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Tool] where [ToolID]=N'" + cmbToolID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Broken.ToolIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbToolID.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(cmbMakerID.Text))
            {
                MessageBox.Show(ToolConstants.Message.Import.MakerCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Maker] where [MakerID]=N'" + cmbMakerID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Maker.MakerIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbMakerID.Focus();
                return false;
            }

            if (Utilities.IsNullOrEmpty(txtTPrice.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Import.PriceCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (decimal.Parse(txtTPrice.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Import.PriceMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTPrice.Focus();
                return false;

            }

            if (Utilities.IsNullOrEmpty(cmbTSupplierID.Text))
            {
                MessageBox.Show(ToolConstants.Message.Import.SupplierCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            dtCheck = BaseDAO.ExecuteQuery("Select * from [333_Supplier] where [SupplierID]=N'" + cmbTSupplierID.Text + "'");
            if (dtCheck.Rows.Count <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Supplier.SupplierIDInvalid, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                cmbTSupplierID.Focus();
                return false;
            }


            if (Utilities.IsNullOrEmpty(txtTQuantity.Text.Trim()))
            {
                MessageBox.Show(ToolConstants.Message.Import.QuantityCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }

            if (int.Parse(txtTQuantity.Text) <= 0)
            {
                MessageBox.Show(ToolConstants.Message.Import.QuantityMustGreaterZero, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtTQuantity.Focus();
                return false;

            }


            #endregion

            o.Date = dtpTDate.Value.Date;
            o.ToolID = cmbToolID.Text.ToString();
            o.MakerID = cmbMakerID.Text.ToString();
            o.PriceJPY = decimal.Parse(txtTPrice.Text);
            o.SupplierID = cmbTSupplierID.Text.ToString();
            o.Quantity = int.Parse(txtTQuantity.Text);
            o.Note = memoTNote.Text;

            return true;
        }

        private void BindDataTools()
        {
            ToolHelper helper = new ToolHelper(new Tools());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemToolID.Add(row[ToolConstants.Entities.Tool.FieldName.ToolID].ToString());

            }
            cmbToolID.AutoCompleteCustomSource = itemToolID;

        }

        private void BindDataSupplier()
        {
            SupplierHelper helper = new SupplierHelper(new Supplier());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemSupplierID.Add(row[ToolConstants.Entities.Supplier.FieldName.SupplierID].ToString());

            }
            cmbTSupplierID.AutoCompleteCustomSource = itemSupplierID;
        }

        private void BindDataToMaker()
        {
            MakerHelper helper = new MakerHelper(new Maker());
            foreach (DataRow row in helper.GetAll().Rows)
            {
                itemMakerID.Add(row[ToolConstants.Entities.Maker.FieldName.MakerID].ToString());

            }
            cmbMakerID.AutoCompleteCustomSource = itemMakerID;

        }

        private void AddTool()
        {
            ImportHelper helper = new ImportHelper(new Import());
            if (GetDataTool(helper.ValueObject))
            {

                if (helper.Insert() > 0)
                {

                    //write Log
                    log.Table = LogConstant.Table.ToolCutting.Import;
                    log.Task = LogConstant.Task.Insert;
                    log.Description = helper.ValueObject.ToolID;
                    log.WriteLog();

                    if (Utilities.MessageConfirmationYesNo(ToolConstants.Message.AddSuccessAndQuestion))
                    {

                        dtpTDate.Value = DateTime.Now.Date;
                        cmbToolID.Text = string.Empty;
                        txtTPrice.Text = string.Empty;
                        cmbTSupplierID.Text = string.Empty;
                        cmbMakerID.Text = string.Empty;
                        txtTQuantity.Text = string.Empty;
                        memoTNote.Text = string.Empty;
                        cmbToolID.Focus();
                    }
                    else
                    {
                        this.Close();
                    }
                }
                else
                {

                    Utilities.MessageErrorOk(ToolConstants.Message.AddFailed);
                }
                if (parent != null)
                {
                    parent._action = 0;
                    parent.BindDatatoGrid();
                }


            }
        }

        #endregion

        private void cmbMakerID_DropDownClosed(object sender, EventArgs e)
        {
            dropDown = false;
            ((System.Windows.Forms.ComboBox)sender).AutoCompleteMode = AutoCompleteMode.Append;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            // Add controls for which Arrow keys => focus is not required.
            if ((!dropDown && (ActiveControl is TextBox || ActiveControl is System.Windows.Forms.ComboBox || ActiveControl is System.Windows.Forms.DateTimePicker)))
            {
                switch (keyData)
                {
                    case Keys.Up:
                    case Keys.Down:

                        bool forward = (keyData == Keys.Down);
                        if (this.ProcessTabKey(forward))
                        {
                            return true;
                        }

                        break;
                }
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }


    }
}